package com.xbongbong.paas.lowcode.impl;

import com.alibaba.fastjson.JSONObject;
import com.xbongbong.paas.abstracts.AbstractLowCodeHandlerFieldService;
import com.xbongbong.paas.enums.FieldTypeEnum;
import com.xbongbong.paas.factory.LowCodeHandlerFieldFactory;
import com.xbongbong.paas.field.FieldAttrEntity;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.StringUtil;
import com.xbongbong.pro.department.pojo.DepartmentUserPojo;
import com.xbongbong.pro.lowcodeexecute.pojo.LowCodeExecuteServicePojo;
import com.xbongbong.sys.domain.entity.UserEntity;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.Map;
import java.util.Objects;

/**
 * @author 吴峰
 * @date 2021/03/18 15:08
 */
@Service("lowCodeHandlerUserService")
public class LowCodeHandlerUserServiceImpl extends AbstractLowCodeHandlerFieldService {

    @PostConstruct
    public void register() {
        LowCodeHandlerFieldFactory.LOW_CODE_HANDLER_FIELD.put(FieldTypeEnum.USER.getType(), this);
    }

    @Override
    public Object handlerField(FieldAttrEntity fieldAttrEntity, JSONObject data, LowCodeExecuteServicePojo lowCodeExecuteServicePojo) throws XbbException {
        String userId = data.getString(fieldAttrEntity.getAttr());
        if (StringUtil.isEmpty(userId)) {
            return null;
        }
        Map<String, UserEntity> userMap = lowCodeExecuteServicePojo.getUserAndDepartmentGetVO().getUserMap();
        UserEntity userEntity = userMap.get(userId);
        DepartmentUserPojo userPojo = new DepartmentUserPojo();
        userPojo.setId(userId);
        if (Objects.nonNull(userEntity)) {
            userPojo.setName(userEntity.getName());
        }
        return userPojo;
    }
}
